package com.wswy.wzcx.ui.njdb

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.blankj.utilcode.util.RegexUtils
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.ProgressDialogObserver
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.ui.loading.ILoadingView
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.ICity
import com.wswy.wzcx.model.PaymentOrder
import com.wswy.wzcx.model.WZCity
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.base.CBaseLoadingFragment
import com.wswy.wzcx.module.base.PayViewModel
import com.wswy.wzcx.module.base.getColor
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.car.choose.ChooseCityActivity
import com.wswy.wzcx.ui.dialog.FullHintAlertDialog
import com.wswy.wzcx.utils.RxUtils
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_njdb_pre_order.*
import timber.log.Timber

/**
 * 确认订单
 */
class NjdbPreOrderFragment : CBaseLoadingFragment() {

    companion object{
        const val TAG = "_NjdbPreOrder"

        private const val REQ_CHOOSE_CITY = 501

        @JvmStatic
        fun newInstance(bundle: Bundle):NjdbPreOrderFragment{
            return NjdbPreOrderFragment().apply {
                arguments = bundle
            }
        }
    }

    override fun getFragmentTitle(): String {
        return "订单确认"
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_njdb_pre_order
    }

    private lateinit var userCarInfo: UserCarInfo

    private lateinit var payViewModel: PayViewModel
    private lateinit var njServiceViewModel: NjServiceViewModel


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val carInfo = arguments?.getParcelable<UserCarInfo?>(Constants.EXTRA_DATA)

        if (carInfo == null){
            finish()
            return
        }

        payViewModel = provideViewModel(PayViewModel::class.java)
        payViewModel.onCreate()


        njServiceViewModel = provideViewModel(NjServiceViewModel::class.java)
        njServiceViewModel.onCreate()

        userCarInfo = carInfo


        fl_address.onClick {
            startActivityForResult(ChooseCityActivity.startPCityChoose(it.context), REQ_CHOOSE_CITY)
        }

        btn_pay.onClick {

           clickSubmit()
        }

        setStep()

        //填充车牌号
        tv_car_no.text = userCarInfo.carNo

        initData()
    }

    override fun getConfigure(): ILoadingView.LoadingConfigure?  = null

    override fun getLoadingFrameId(): Int = R.id.rl_content



    private fun initData(){

        njServiceViewModel.getUserLiveData().observe(this, Observer {
            it?.run {

                et_user_phone.setText(this.mobile)
            }
        })

        njServiceViewModel.getPreOrder(userCarInfo.id).observe(this, Observer {

            it?.run {

                if (inLoading()){
                    //加载中
                    showLoading(true)
                }else if (isOk()){
                    //成功
                    showData()

                    tv_amount_mony.text = getString(R.string.amount_args,data?.amount)

                    tv_nj_price.text = getString(R.string.amount_args,data?.amount)

                }else if (hasError()){
                    showError(VOMessage.create(null))
                }

            }

        })

        payViewModel.getOrderPayResultLiveData().observe(this, Observer {

            it?.runCatching {

                if (status){
                    //成功
                    startPaySuccess(order)
                }
                payViewModel.consumeOrderPayResult()
            }

        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == REQ_CHOOSE_CITY){

            val city = data?.getParcelableExtra<ICity>(Constants.EXTRA_DATA_CHOOSE_CITY)
            if (city is WZCity ) {

                Timber.e("city  $city")
                tv_address_city.text = "${ if(TextUtils.isEmpty(city.pname)) "" else "${city.pname}-"}${city.cityName}"
            }

        }

    }


    private fun setStep(){
        view_num_1.setImageResource(R.drawable.order_paysucessed)
        view_num_2.setImageDrawable(NumDrawable(2.toString(),getColor(R.color.colorPrimary)))
        view_num_3.setImageDrawable(NumDrawable(3.toString(),getColor(R.color.color_normal_hint)))
        view_num_4.setImageDrawable(NumDrawable(4.toString(),getColor(R.color.color_normal_hint)))

        view_line_1.setBackgroundColor(getColor(R.color.colorPrimary))
        view_line_2.setBackgroundColor(getColor(R.color.color_line))
        view_line_3.setBackgroundColor(getColor(R.color.color_line))


        tv_step_1.setTextColor(getColor(R.color.textColorPrimary))
        tv_step_2.setTextColor(getColor(R.color.textColorPrimary))
    }


    private fun startPaySuccess(order: PaymentOrder){

        //删除本地文件

        NjdbUtils.deleteDir(requireContext(),userCarInfo.id)

        //支付成功，跳转到进度列表

        ModuleActivity.getTargetIntent(requireContext(),NjdbStepFragment.TAG,Bundle().apply {

            putParcelable(Constants.EXTRA_DATA,userCarInfo)
            putParcelable("extra.order",order)

        })?.let {
            startActivity(it)
            finish()

        }

    }


    private fun clickSubmit(){
        val map = HashMap<String,String>()


        val name = et_user_name.text
        val phone = et_user_phone.text
        val city = tv_address_city.text
        val address = et_user_address.text

        if (TextUtils.isEmpty(name)){
            ToastUtils.showText("请输入联系人姓名")
            return
        }

        if (TextUtils.isEmpty(phone)){
            ToastUtils.showText("请输入联系电话")
            return
        }


        if (!RegexUtils.isMobileSimple(phone)){
            ToastUtils.showText("联系电话不正确，请重新输入")
            return
        }

        if (TextUtils.isEmpty(city)){
            ToastUtils.showText("请选择城市")
            return
        }

        if (TextUtils.isEmpty(address)){
            ToastUtils.showText("请输入详细地址")
            return
        }

        //先上传图片
        map["contacts"] = name.toString()
        map["mobile"] = phone.toString()
        map["address"] = "$city-$address"
        map["carNo"] = userCarInfo.carNo
        map["payType"] = "${payLayout.getPayStyle().code}"



        FullHintAlertDialog(context!!)
                .setDialogMessage(R.string.msg_njdb_pay1,R.string.msg_njdb_pay2,R.string.msg_njdb_pay3)
                .setDelayNext(5)
                .setLeftText(R.string.think_about, null)
                .setRightText(R.string.continue_pay) {


                    submit(map)

                }.show()

    }

    private fun submit(map: HashMap<String,String>){

        //提交订单

        val files = NjdbUtils.getImgFiles(requireContext(),userCarInfo.id).mapKeys {
            when(it.key){
                "Z1" -> "compulsoryInsuranceCopy"
                else -> it.key
            }
        }


        Single.just(map).observeOn(Schedulers.io()).flatMap { data ->

            kotlin.runCatching {
                Api.get().uploadFiles("njdb",files).compose(RxUtils.switch2io()).blockingGet()?.forEach { (t, u)
                    ->
                    u?.objectKey?.let {
                        data[t] = it
                    }
                }
            }
            Single.just(data)
        }.flatMap {
            Api.get().createInspection(it)
        }.subscribe(object : ProgressDialogObserver<PaymentOrder>(requireContext(),"提示","正在提交订单，请稍后"){
            override fun onApiResult(t: PaymentOrder?) {

                if (t != null && t.isSuccess){
                    //成功
                    //必须，设置金额
                    t.payStyle = payLayout.getPayStyle().code
                    t.bizType = "njdb"
                    if (!isFinish && isVisible){
                        //拉起支付
                        payViewModel.startPay(requireActivity(),t)
                        //startPaySuccess(t)
                    }

                }else{
                    ToastUtils.showText("创建订单失败，请稍后重试")
                }

            }

            override fun onApiError(result: BaseResult<*>?) {
                toastErrorMsg(result)
            }
        })

    }


}